package com.zzk.im.tool;

import com.zzk.im.hx.model.HXResponseObject;
import com.zzk.im.hx.service.HXHttpService;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import java.util.HashMap;
import java.util.Map;

public class TokenTool {

    private static Token token;

    private static long lastGetTime;


    static public String getToken(Boolean required) {
        return checkToken(required).getToken();
    }

    static public String getToken() {
        return checkToken(false).getToken();
    }

    static private Token checkToken(boolean required) {

        if (required == false && token != null && token.isExpire() == false) {
            return token;
        }


        synchronized (TokenTool.class) {

            //短时间多次获取token会被封号(设置间隔为5秒)
            if (System.currentTimeMillis() - lastGetTime  <5000){
                return token;
            }

            try {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("grant_type", "client_credentials");
                param.put("client_id", Constant.APP_CLIENT_ID);
                param.put("client_secret", Constant.APP_CLIENT_SECRET);

                WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
                HXHttpService httpService = currentWebApplicationContext.getBean(HXHttpService.class);
                HXResponseObject res = httpService.request(Constant.URR_TOKEN, Constant.HTTP_METHOD_POST, param, false, null);

                if (res != null && res.getAccess_token() != null && res.getExpires_in() != null && res.getExpires_in() > 0) {
                    token = new Token(res.getAccess_token(), res.getExpires_in() * 1000 + System.currentTimeMillis());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lastGetTime = System.currentTimeMillis();
            }
        }

        return null;
    }

    public static class Token {
        private String token;
        private Long expire;

        public Token() {
        }

        public Token(String token, long expire) {
            this.token = token;
            this.expire = expire;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public Long getExpire() {
            return expire;
        }

        public void setExpire(Long expire) {
            this.expire = expire;
        }

        public boolean isExpire() {
            return expire == null || System.currentTimeMillis() > expire;
        }
    }
}